#include <rgb_to_grayscale.hpp>

namespace ohe_framework {
bool convertToGrayscale(ImageMatrixUchar &input,ImageMatrixUchar &output,int mode)
{
	if((!input.isMatrixFree()))
	{
	  if(input.getNoOfChannels()==3)
	  {
	    if(output.isMatrixFree())
		{
		  output.newMatrix(input.getCols(),input.getRows(),1);
		  if(grayscale(input,output,mode))
		  {
		    return true;
		  }
		  else
		  {
		    output.releaseMatrix();
			return false;
		  }
		}
		else
		{
		  if(input.getRows()==output.getRows())
		  {
		    if(input.getCols()==output.getCols())
			{
			  if(input.getElemSize()==output.getElemSize())
			  {
                              return grayscale(input,output,mode);
			  }
			  else
			  {
			    printErrorMessage("Input Matrix and output matrix datasize not matched");
				return false;
			  }
			}
			else
			{
			  printErrorMessage("Input Matrix and output matrix cols not matched");
			  return false;
			}			
		  }
		  else
		  {
		    printErrorMessage("Input Matrix and output matrix rows not matched");
	        return false;
		  }
		}
	  }
	  else
	  {
	    printErrorMessage("Input Matrix is not color matrix");
	    return false;
	  }
	}
	else
	{
	  printErrorMessage("Input Matrix is not allocated");
	  return false;
	}
	
}
bool grayscale(ImageMatrixUchar &input,ImageMatrixUchar &output,int mode)
{
  float r_coff,g_coff,b_coff;
  if(mode==NTSC)
  {
        r_coff = 0.299;
	g_coff = 0.587;
	b_coff = 0.114;	
  }
  else if(mode==HDTV)
        {
            r_coff = 0.2126;
            g_coff = 0.7152;
            b_coff = 0.0722;	
        }
        else
        {
            printErrorMessage("Input method is not defined");
            return false;
        }
  unsigned char *in_data= input.getDataPointer();
  unsigned char *out_data = output.getDataPointer();
  unsigned int rows = input.getRows();
  unsigned int cols = input.getCols();
  unsigned int in_widthstep = input.getWidthstep();
  unsigned int out_widthstep = output.getWidthstep();
  for(short i=0;i<rows;i++)
  {
    for(short j=0;j<cols;j++)
    {
        out_data[i*out_widthstep+j]=(unsigned char)(b_coff*in_data[i*in_widthstep+j*3+0]+
                                         g_coff*in_data[i*in_widthstep+j*3+1]+
                                         r_coff*in_data[i*in_widthstep+j*3+2]);
    }
  }
  return true;
}
} // end namesapce ohe_framework
